#!/bin/bash

# This script help to
#  check the process of the memcached is running and reachable within timeout,
#  if it is not, it will restart the service and write to error log.
#  else, do nothing.

# Function: return 0 = Not OK, 1 = OK
check_service() {
    timeout 5 bash -c "echo > /dev/tcp/127.0.0.1/11211"
    
    if [ $? != 0 ]; then
        return 0
    else
        return 1
    fi
}

if check_service ; then
    SERVICE_RESTART_CMD="/etc/init.d/memcached restart"
    ERROR_LOG="/var/log/memcached/memcached-error.log"
    
    echo "Service not OK, service restarting ..."
    echo `$SERVICE_RESTART_CMD`

    sleep 5

    if check_service ; then

        MESSAGE="Service still not OK after restarted"
        SEVERITY="error"
    else

        MESSAGE="Service OK after restarted"
        SEVERITY="notice"
    fi

    NOW=$(date +"%Y-%m-%d %T")
    ERROR_MESSAGE="$NOW - $SEVERITY - service:memcached host:$(hostname) message:$MESSAGE"

    echo $ERROR_MESSAGE >> $ERROR_LOG
    echo $ERROR_MESSAGE

else    
    echo "Service OK"
fi
 